const { Novel, Chapter } = require('../sql/models'); // 假设模型文件中已经定义了 Novel 和 Chapter 模型
const { Op, Sequelize } = require('sequelize'); // 修改: 正确引入 Sequelize

// 获取小说列表接口
const getNovelList = async (req, res) => {
    const { query } = req.query;
    try {
        let novels;
        if (query) {
            novels = await Novel.findAll({
                where: {
                    [Op.or]: [
                        { title: { [Op.like]: `%${query}%` } },
                        { author: { [Op.like]: `%${query}%` } },
                        { summary: { [Op.like]: `%${query}%` } } // 修改: 使用 summary 字段
                    ]
                }
            });
        } else {
            novels = await Novel.findAll();
        }
        if (novels.length === 0) {
            return res.status(404).json({ error: '资源未找到' });
        }
        res.json(novels);
    } catch (error) {
        res.status(500).json({ error: '服务器内部错误' });
    }
};

const getNovelChapters = async (req, res) => {
    const { novelId } = req.params;
    try {
        console.log(`Fetching chapters for novel ID: ${novelId}`); // 新增: 添加日志
        const chapters = await Chapter.findAll({ where: { novel_id: novelId } });
        if (chapters.length === 0) {
            return res.status(404).json({ error: '资源未找到' });
        }
        res.json(chapters);
    } catch (error) {
        console.error('Error executing query:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
};

const getNovelDetails = async (req, res) => {
    const { novelId } = req.params;
    try {
        console.log(`Fetching details for novel ID: ${novelId}`); // 新增: 添加日志
        const novel = await Novel.findByPk(novelId);
        if (!novel) {
            return res.status(404).json({ error: '资源未找到' });
        }
        res.json(novel);
    } catch (error) {
        console.error('Error executing query:', error);
        res.status(500).json({ error: '服务器内部错误' });
    }
};

const getRandomNovels = async (req, res) => {
    try {
        const novels = await Novel.findAll({
            order: Sequelize.literal('RAND()'), // 修改: 使用 Sequelize.literal
            limit: 10 // 限制结果数量为10条
        });
        if (novels.length === 0) {
            return res.status(404).json({ error: '资源未找到1' });
        }
        res.json(novels);
    } catch (error) {
        console.log(error,'error')
        res.status(500).json({ error: '服务器内部错误' });
    }
};

module.exports = {
    getNovelList,
    getNovelChapters,
    getNovelDetails,
    getRandomNovels // 新增: 导出 getRandomNovels 函数
};